<?php
/**
 * 用户基础模型
 */
namespace Common\Model;
use Think\Cache\Driver\Db;
use Think\Model;
use Common\Model\EXPModel;
use Common\Model\PointModel;
use Common\Model\MoneyModel;
use Common\Model\SmsModel;
use ORG\Util\Date;
class UserModel extends BaseModel{



	//用户头头像分组
	const USER_HEADPIC_DEVIDE  = 1000;

	//用户操作预置次数限定类型
	const LIMIT_TYPE_DAILY		= 1;//日
 	const LIMIT_TYPE_WEEKLY		= 2;//周
 	const LIMIT_TYPE_MONTHLY	= 3;//月
 	const LIMIT_TYPE_YEARLY		= 4;//年
 	const LIMIT_TYPE_FULLLIFE	= 5;//全生命周期


	//用户状态
	const USER_STATUS_All 		= 0;//
 	const USER_STATUS_NORMAL 	= 1;//正常用户
 	const USER_STATUS_SHUTUP 	= 2;//禁言用户
 	const USER_STATUS_DENYLOGIN= 3;//禁止登陆

	//性别
	const USER_SEX_ALL 			= 0;//全部
	const USER_SEX_MALE 		= 1;//男
	const USER_SEX_FEMALE 		= 2;//女
	const USER_SEX_OTHER 		= 3;//其他

	const FIELD_SEPARATOR   ="@@@";
	const LINE_SEPARATOR    ="###";

	public static function getUserStatus(){
		return array(
			self::USER_STATUS_All         =>'全部',
			self::USER_STATUS_NORMAL      =>'正常用户',
			self::USER_STATUS_SHUTUP      =>'禁言用户',
			self::USER_STATUS_DENYLOGIN   =>'禁止登陆'
		);
	}

	public static function getUserSex(){
		return array(
			self::USER_SEX_ALL            =>'全部',
			self::USER_SEX_MALE           =>'男',
			self::USER_SEX_FEMALE         =>'女',
			self::USER_SEX_OTHER          =>'保密'
		);
	}

	private static $instance=null;
	public static function getInstance(){
		if(!self::$instance){
			self::$instance=M('u_user_base',null,DB_MAIN_CFG);
		}
		return self::$instance;
	}

	private static $vipLogInstance=null;
	public static function getVipLogInstance(){
		if(!self::$vipLogInstance){
			self::$vipLogInstance=M('u_vip_log',null,DB_MAIN_CFG);
		}
		return self::$vipLogInstance;
	}



    public static function getUserVipInfo($uid){
		return self::getInstance()->where("uid={$uid}")->field("uid,nickname,vip,vipEndTime,vipEventJoinTimes")->find();
	}


	public function __construct(){
	}
	
	/* 获取微信平台请求的信息
	 * uid 用户ID
	 * self 0|1 0是自己 1是别人
	 * return  "data": {
        "sex": "4",
        "sexHtml": "",
        "userStatus": "2",
        "regTime": "1970-01-01  08:00:00",
        "lastLoginTime": "1970-01-01  08:00:00",
        "level": "2",
        "levelHtml": "老枪",
        "userTag": "1",
        "userTagHtml": "普通用户",
        "province": "820000",
        "city": "0",
        "EXP": "0",
        "bindPhone": "15657818590",
        "birthday": "0000-00-00",
        "consumeMoney": "0",
        "email": "",
        "lastLoginIP": "",
        "money": "0",
        "nickname": "Rick.Sun",
        "point": "100",
        "realName": "东野",
        "uid": "7",
        "userName": "Rick.Sun",
        "address": "澳门..."
    }
	*/
	public static function getUser($uid=0, $self=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$uid){
			return $dataFailure;
		}

		$userM=self::getInstance();
		$uinfo=$userM->where("uid={$uid}")->find();
		if(!$uinfo){
			$dataFailure['msg']='指定编号的用户不存在';
			return $dataFailure;
		}else{

			//获取用户微信账号信息
			$uinfoWeixin=M('u_user_weixin',null,DB_MAIN_CFG)->where("uid={$uid}")->find();
			$info = array();
			//卡券数量
			$cardNum = M('card_code',null,DB_MAIN_CFG)->where("uid={$uid} and status=1")->count();

			if($self == 0) {
				$info = UserModel::getUserNewMessageStatus($uid);
			}



			$userLevel 	= getLevelKv();
			$userTag 	= getUTagKv();
			$userVip    = getVipKv();

			$cfgSexArr=self::getUserSex();//C('USER_SEX');
			$cfgUserStatus=self::getUserStatus();

			$info['sex']		=$uinfo['sex'];
			$info['sexHtml']	=trim($cfgSexArr[$uinfo['sex']]);
			$info['userStatus']	=$cfgUserStatus[$uinfo['userStatus']];
			$info['regTime']	=date('Y-m-d  H:i:s',$uinfo['regTime']);
			$info['lastLoginTime']=date('Y-m-d  H:i:s',$uinfo['lastLoginTime']);



			$info['level'] 		= $uinfo['level'];
			$info['levelHtml']	= $userLevel[$uinfo['level']];

			if ($uinfo['vipEndTime']>time() && $uinfo['vipEventJoinTimes']>0)
			{
				$uinfo['vip']=1;
				$info['vipEndTime']=date('Y-m-d  H:i:s',$uinfo['vipEndTime']);
				$info['vipEventJoinTimes']=$uinfo['vipEventJoinTimes'];
			}else{
				$uinfo['vip']=0;
				$info['vipEndTime']=0;
				$info['vipEventJoinTimes']=0;
			}
			$info['vip']		= $uinfo['vip'];
			$info['vipHtml']	= $userVip[$uinfo['vip']];

			
			$info['userTag'] 	= $uinfo['userTag'];
			$info['userTagHtml'] = $userTag[$uinfo['userTag']];
			$info['province'] 	= $uinfo['province'];
			$info['city'] 		= $uinfo['city'];
			$info['district'] 	= $uinfo['district'];
			$info['street']		= $uinfo['street'];
			$info['EXP']		= $uinfo['EXP'];
			$info['bindPhone'] 	= $uinfo['bindPhone'];
			$info['birthday'] 	= $uinfo['birthday'];
			$info['consumeMoney'] = $uinfo['consumeMoney'];
			$info['email'] 		= $uinfo['email'];
			$info['lastLoginIP'] = $uinfo['lastLoginIP'];
			$info['money'] 		= $uinfo['money'];
			$info['nickname'] 	= $uinfo['nickname'];
			$info['point'] 		= $uinfo['point'];
			$info['realName'] 	= $uinfo['realName'];
			$info['uid'] 		= $uinfo['uid'];
			$info['userName'] 	= $uinfo['userName'];
			$info['userStatus'] = $uinfo['userStatus'];
			$info['realName'] 	= $uinfo['realName'];
			$info['personal']	= $uinfo['personal'];
			$info['cardNum']	= $cardNum;
			$info['unionID'] 	= $uinfoWeixin['WX_unionID'];
			$info['openid']		= $uinfoWeixin['WX2_openID'];
			$info['subscribeOpenID']	= $uinfoWeixin['WX2_openID'];
			$info['app_openID']	= $uinfoWeixin['app_openID'];

			//$regionKv = include_once(WEB_ROOT.'/data/area_info/'.$uinfo['province'].'.php');
			$info['address']=$uinfo['address'];

			$dataSuccess['data']=$info;
		}
		return $dataSuccess;
	}


	/**
	 * 获取用户最新状态信息
	 * User: Rick.Sun.<sunwgjj@126.com>
	 * Return: void
	 * Address: 浙江宣逸网络科技有限公司
	 * @param $uid
	 * @return mixed
	 */
	function getUserNewMessageStatus($uid){
		//处理用户小红点
		//用户新消息
		$info['newNotice'] = NoticeModel::checkRedPrompt($uid);
		$info['newEvent'] = $info['newPointMall'] = 0;
		$tipsRow = M('red_prompt', null, DB_MAIN_CFG)->where("uid={$uid}")->find();
		$eventsMaxID = M('e_events', null, DB_MAIN_CFG)->field('id')->where("del=0 AND clientShow = 1")->order(" id desc")->find();//获取活动最大值
		$pointMallMaxID = M('point_mall', null, DB_MAIN_CFG)->field('id')->where("clientShow = 1")->order(" id desc")->find();//获取积分商城最大值
		if (!$tipsRow) {
			$info['newEvent'] = $info['newPointMall'] = 1;
			M('red_prompt', null, DB_MAIN_CFG)->add(array('uid' => $uid, 'eID' => $eventsMaxID['id'], 'pointMailID' => $pointMallMaxID['id']));
		} else {
			if ($eventsMaxID['id'] > $tipsRow['eID']) {
				$info['newEvent'] = 1;
				M('red_prompt', null, DB_MAIN_CFG)->where("uid={$uid}")->setField('eID', $eventsMaxID['id']);
			}
			if ($pointMallMaxID['id'] > $tipsRow['pointMailID']) {
				$info['newPointMall'] = 1;
				M('red_prompt', null, DB_MAIN_CFG)->where("uid={$uid}")->setField('pointMailID', $pointMallMaxID['id']);
			}
		}
		return $info;
	}

	

	/**
	 * 获取用户经常会变的信息：积分，余额，消费余额，经验
	 * Author: shijy
	 * @param $uid
	 * @return array
	 */
	public static function getUserChangeFul($uid){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$data= self::getInstance()->field('point,money,consumeMoney,EXP,level')->where("uid={$uid}")->find();
		if(!$data){
				$dataFailure['msg']='找不到指定用户';
				return $dataFailure;
			}

		$dataSuccess['data']=$data;
		return $dataSuccess;
	}

	/**
	 *
	 * 用于用户登陆
	 * phone 用户手机号码 必填
	 * password 用户密码 必填
	 * clientFrom 客户端来源
	 * Author: RickSun
	 * return
	 */
	public static function getUserByPhoneAndPassword($phone,$password,$clientFrom=0){

		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(!$phone || !$password){
			return $dataFailure;
		}

		if(!filedPreMatch('phone', $phone)){
			$dataFailure['msg'] = '手机号码格式错误';
			return $dataFailure;
		}

		$password = passwordEncryption($password);
		$userM=self::getInstance();
		$uinfo=$userM->where("bindPhone='{$phone}' AND userPWD = '{$password}'")->find();
		if(!$uinfo){
			$dataFailure['msg']='用户手机或密码错误';
			return $dataFailure;
		}else{

			//登陆得积分判断
			$tip = self::addUserValByAction($uinfo['uid'],OPT_LOGIN);
			self::addLoginLog($uinfo['uid'], $clientFrom);
			$userinfo = UserModel::getUser($uinfo['uid']);
			$userinfo['ext'] = $tip['ext'];
			return $userinfo;
		}
	}


	/**
	 * 用户签到
	 * Author: shijy
	 * @param $uid
	 * @return mixed
	 */
	public static	function userSign($uid){
		if(!USER_HOME_MYSIGN_ENABLE){
			return false;
		}
		$loginTime=time();

		$signM = M('u_sign',null,DB_MAIN_CFG);
		$where = "uid={$uid}";
		$data = $signM->where($where)->find();
		$lastLoginTime=$data['todaySignTime']+0;
		$lastTime = date('Ymd',$lastLoginTime);
		$nowTime = date('Ymd',$loginTime);

		if($nowTime == $lastTime){//同一天，退出
			return false;
		}
		$todayFirstTime =1;
		//签到奖励次数功能开关（月满签和特殊时间段）
		$signRewardSwitch = S("signRewardSwitch");
		if(!$signRewardSwitch){
			$signRewardSwitch = M("cfg_config",null,DB_MAIN_CFG)->where("cfgName = 'SIGN_REWARD_SWITCH'")->getField("cfgValue");
			S('signRewardSwitch',$signRewardSwitch);
		}
		$signRewardSwitch = explode(',',$signRewardSwitch);

		if($data){
			if(date('m',$loginTime) == date('m',$lastLoginTime)){		//是否为同一个月
				if($data['signDay']){
					$data['signDay'] .= ",".date('j',$loginTime);
				} else{
					$data['signDay'] = date('j', $loginTime);
				}
				$data['signMonthTimes'] += 1;
				$newData = array(
					"signDay"=>$data['signDay'],
					"signMonthTimes"=>$data['signMonthTimes'],
				);
			} else{
				$newData = array(
					"signMonthTimes"=>1,
					"signDay"=>date('j',$loginTime),
				);
			}

			$signAllTimes = $data['signAllTimes']+1;
			$newData['todaySignTime']= $loginTime;
			$newData['todaySignRank']= 0;
			$newData['signAllTimes']= $signAllTimes;

			$toastContent = "";
			//累计签到
			if(SIGN_REWARD_CUMULATIVE){
				$signLuckyTimes = 0;
				if(SIGN_REWARD_CUMULATIVE_DAY>0){
					$signLuckyTimes = floor($signAllTimes/SIGN_REWARD_CUMULATIVE_DAY) ;	//累计签到奖励抽奖次数
				}
				$newData['signLuckyTimes'] = $signLuckyTimes;
				if($signLuckyTimes > $data['signLuckyTimes']){
					$toastContent .= "<br/>".SIGN_REWARD_CUMULATIVE_DAY."日累计签到，抽奖次数+1";
				}
			}

			//月满签
			if($signRewardSwitch[0]==1 && $data['signMonthTimes'] == date('t',time())) {
				$data['monFullSignTimes'] += 1;                //月满签奖励抽奖次数
				$newData['monFullSignTimes'] = $data['monFullSignTimes'];
				$toastContent .= "<br/>当月满签，抽奖次数+1";
			}

			//特殊时间段
			if($signRewardSwitch[1]==1){					//特殊时间期间奖励抽奖次数功能开关
				if($loginTime >= $signRewardSwitch[3] and $loginTime <= $signRewardSwitch[4]){
					$data['specialLuckyTimes'] += $signRewardSwitch[2];			//特殊时间期间，每天签到+抽奖机会
					$newData['specialLuckyTimes'] = $data['specialLuckyTimes'];
					$toastContent .= "<br/>每日签到活动，抽奖次数+".$signRewardSwitch[2];
				}
			}

			//连续登录+1,判断积分奖励情况
			$nextDayBeginTime = mktime(23,59,59,date('m',$lastLoginTime),date('d',$lastLoginTime),date('Y',$lastLoginTime));
			$nextDayEndTime = strtotime("+1 day",$nextDayBeginTime);
			if($loginTime > $nextDayBeginTime && $loginTime <= $nextDayEndTime){
				$continueDay = $data['continueDay']+1;
			} else {
				$continueDay = 1;
			}
			$newData['continueDay'] = $continueDay;
			$signM->where($where)->setField($newData);
			session("signToast",$toastContent);
		}else{
			$signAllTimes = 1;
			$newData = array(
				'uid'				=> $uid,
				'signAllTimes'		=> $signAllTimes,
				'signMonthTimes'	=> 1,
				'signDay'			=> date('j',$loginTime),
				'todaySignRank' 	=> 0,
				'todaySignTime' 	=> $loginTime,
				'signLuckyTimes'	=> 0,
				'monFullSignTimes'	=> 0,
				'specialLuckyTimes'	=> 0,
				'continueDay'		=> 1,
			);
			//特殊时间段
			if($signRewardSwitch[1]==1){					//特殊时间期间奖励抽奖次数功能开关
				if($loginTime >= $signRewardSwitch[3] and $loginTime <= $signRewardSwitch[4]){
					$newData['specialLuckyTimes'] = $signRewardSwitch[2];	//特殊时间期间，每天签到+抽奖机会
					$toastContent = "<br/>每日签到活动，抽奖次数+".$signRewardSwitch[2];
					session("signToast",$toastContent);
				}
			}
			$continueDay = 1;
			$signM->add($newData);
		}

		$extra = M('lucky_prize',null,DB_MAIN_CFG)
			->where("type=".SignLuckyModel::PRIZE_TYPE_SIGN_CONTINUE." and prizeType=".ELEMENT_TYPE_POINT)
			->field("prizeRank,extra")
			->select();
		$point = 0;
		if($extra && $todayFirstTime == 1 ){
			foreach ($extra as $val){
				if($continueDay % $val['prizeRank'] == 0){
					$point += $val['extra'];
					//签到奖励积分
					if($val['extra'] > 0){
						self::plusPoint($uid,-1,$val['extra'],OPT_CONTINUE_SIGN);
					}
				}
			}
		}

		$info['todayFirstTime'] = $todayFirstTime;
		$info['point'] = $point;

		if($info['todayFirstTime']==1){
			//签到日志
			self::addSignLog($uid,$info['point'],$signAllTimes);
			//日签到排行
			self::todaySignRank($uid);
			//登录 变动签到排名
			self::signRanking();
		}
		return $info;
	}

	/**
	 * 获取用户签到次数和奖励积分, 并计算抽奖次数
	 * Author:wwl
	 * return
	 */
	public static function getSignTimes($uid){
		$signM = M('u_sign',null,DB_MAIN_CFG);
		$data = $signM->where("uid={$uid}")->field('signAllTimes,signMonthTimes,signDay,usedTimes,todaySignRank,monFullSignTimes,signLuckyTimes,specialLuckyTimes')->find();
		$time = time();
		$luckyTimes = $data['signLuckyTimes'] + $data['monFullSignTimes'] + $data['specialLuckyTimes'];	//总抽奖次数
		if($luckyTimes <= $data['usedTimes']){
			$data['luckyTimes'] = 0;
		}else $data['luckyTimes'] = $luckyTimes-$data['usedTimes'];

		$start = mktime(0,0,0,date("m",$time),date("d",$time),date("Y",$time));
		$end = mktime(23,59,59,date("m",$time),date("d",$time),date("Y",$time));
		$data['signPoint'] = M('u_sign_log',null,DB_MAIN_CFG)->where("uid={$uid} and addTime between {$start} and {$end} and addPoint > 0")->getField("addPoint");
		$data['loginPoint'] = M('cfg_value_get',null,DB_MAIN_CFG)->where("action=".OPT_LOGIN.' and status=1')->getField("point");

		return $data;
	}


	/**
	 * 排名统计
	 * author: wwl <wuwl@soe-soe.com>
	 * Address: 浙江宣逸网络科技有限公司
	 */
	public static function signRanking(){
		$begin = microtime(true);
		$lastRankTime = S("signRankTime")+0;
		$spacingTime = $begin-$lastRankTime;	//实际间隔时间
		$spacingMaxTime = 300;			//最大间隔时间
		if($spacingTime > $spacingMaxTime){
			S("signRankTime", microtime(true));
			$signM = M('u_sign',null,DB_MAIN_CFG);
//			$dataOuterFile="/home/www/star/server/data/userSign_".$uid;
			$dataOuterFile=C('LOAD_DATA_DIR')."userSign";
			unlink($dataOuterFile);

			$count = $signM->count();
			$items = 10000;
			$parts = ceil($count/$items);

			for ($i=0;$i<$parts;$i++){
				$startItem = $i*$items;
				$sql = $signM->order('signAllTimes DESC,uid ASC')->field('uid,signAllTimes')->limit($startItem,$items)->select();
				foreach($sql as $key => $val){
					$sql[$key]['rank'] = $startItem+$key+1;
					$str = $val['uid'].self::FIELD_SEPARATOR.$val['signAllTimes'].self::FIELD_SEPARATOR.$sql[$key]['rank'].self::LINE_SEPARATOR;
					file_put_contents($dataOuterFile,$str,FILE_APPEND);
				}
				unset($sql);
			}

			$sql = <<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO table `%s`.u_sign_rank FIELDS TERMINATED BY '%s' LINES TERMINATED BY '%s' (uid,signAllTimes,rank);
SQL;
			$sql = sprintf($sql,$dataOuterFile,C('DB_NAME'),self::FIELD_SEPARATOR,self::LINE_SEPARATOR);
			$signM->execute($sql);
		}
		return;
	}

	/**
	 * 读取排名
	 * author:wwl
	 */
	public static function getSignRank($uid){
		$rank = M('u_sign_rank',null,DB_MAIN_CFG)->where("uid={$uid}")->getField("rank");
		return $rank;
	}

	/**
	 * 读取签到相关所有数据信息
	 * author: wwl <wuwl@soe-soe.com>
	 * Return: array
	 * Address: 浙江宣逸网络科技有限公司
	 */
	public static function sign($uid,$from=CLIENT_FROM_PC){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$uid){
			return $dataFailure;
		}
		$signInfo = self::getSignTimes($uid);				  //取签到日子、总签到次数、月签到次数、日签到排名、奖励积分(u_sign)
		$signDay = explode(',',$signInfo['signDay']);
		$weekAndDay = UtilsModel::getWeekAndDay(time());      //本月第一天星期几及本月天数,本次登录日期
		$rank = self::getSignRank($uid);					  //取总排名(u_sign_rank)

		$data['signInfo'] = $signInfo;
		$data['signDay'] = $signDay;
		$data['weekAndDay'] = $weekAndDay;
		$data['rank'] = $rank;

		if($from == CLIENT_FROM_PC){
			$basePic = SignLuckyModel::getBasePicAndRegulations();//取底图(lucky_Prize)
			$set = SignLuckyModel::getLuckyPrizeNote();           //奖品说明(lucky_prize)
			$myPrize = UserModel::getLuckyPrizeLog($uid,SignLuckyModel::PRIZE_TYPE_SIGN_LUCKY,1,8,CLIENT_FROM_PC);//我的奖品(u_lucky_log)
			$data['basePic'] = $basePic;
			$data['set'] = $set;
			$data['myPrize'] = $myPrize;
		}
		$dataSuccess['data'] = $data;
		return $dataSuccess;
	}

	/**
	 *
	 * 通过手机号码 注册账号
	 * phone 		用户手机号码 必填
	 * password 	用户密码 必填
	 * nickname 	用户昵称 必填
	 * code 		验证码 必填
	 * regFrom 		客户端注册来源
	 * Author: RickSun
	 * return
	 */
	public static function registerUserByPhone($phone, $password, $nickname, $code,$regFrom=0){
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(!$phone || !$password){
			return $dataFailure;
		}

		if(!filedPreMatch('phone', $phone)){
			$dataFailure['msg'] = '手机号码格式错误';
			return $dataFailure;
		}
		if(UtilsModel::strlen($code) != 4){
			$data['msg'] = '请填写正确的验证码';
			return $dataFailure;
		}
		if(UtilsModel::strlen($nickname)<C('NICKNAME_LENGTH_MIN') || UtilsModel::strlen($nickname)>C('NICKNAME_LENGTH_MAX')){
			$dataFailure['msg'] = '昵称长度不符合要求：'.C('NICKNAME_LENGTH_MIN').'-'.C('NICKNAME_LENGTH_MAX');
			return $dataFailure;
		}
		if(UtilsModel::strlen($password) < 6 || UtilsModel::strlen($password) >32 ){
			$dataFailure['msg'] = '密码格式不正确！支持6-32字节';
			return $dataFailure;
		}

		$codeinfo = SmsModel::getCode($phone);
		if($codeinfo['code'] != $code){
			$dataFailure['msg'] = '请填写正确的验证码';
			return $dataFailure;
		}
		M('t_sms_log', null, DB_MAIN_CFG)->where(" phone = '{$phone}' AND code = '{$code}' AND type = 1 AND status = 1")->save( array('status'=>2) );

		$password = passwordEncryption($password);
		$userM=M('u_user_base',null,DB_MAIN_CFG);
		$uinfo=$userM->where(" bindPhone='{$phone}' ")->find();
		if($uinfo){
			$dataFailure['msg']='该手机号码已存在';
			return $dataFailure;
		}else{
			$user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
			$user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];
			$data['bindPhone'] 	= $phone;
			$data['userPWD']	= $password;
			$data['regTime']	= time();
			$data['regIP']		= $user_IP;
			$data['regFrom']	= $regFrom;
			$data['nickname']	= $nickname;
			$data['province']	= "330000";		//注册 默认选择浙江宁波
			$data['city']		= "330200";		//注册 默认选择浙江宁波
			$uid = $userM->add($data);

			$tip = self::addUserValByAction( $uid,OPT_LOGIN);
			self::addLoginLog($uid,CLIENT_FROM_WX );
			//用户指数表新增对象
			$obj = array(
				'uid'		=> $uid,
				'nickname'	=> $nickname,
			);
			M('statistic_user_like',null,DB_MAIN_CFG)->add($obj);

			$userinfo = UserModel::getUser($uid);
			$userinfo['ext'] = $tip['ext'];
			return $userinfo;
		}
	}

	/**
	 *
	 * 重置密码 通过手机号
	 * phone 用户手机号码 必填
	 * password 用户密码 必填
	 * code 验证码 必填
	 * Author: RickSun
	 * return
	 */
	public static function resetUserPasswordByPhone($phone, $password, $code){
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(!$phone || !$password){
			return $dataFailure;
		}

		if(!filedPreMatch('phone', $phone)){
			$dataFailure['msg'] = '手机号码格式错误';
			return $dataFailure;
		}
		if(UtilsModel::strlen($code) != 4){
			$data['msg'] = '请填写正确的验证码';
			return $dataFailure;
		}
		if(UtilsModel::strlen($password) < 6 || UtilsModel::strlen($password) >32 ){
			$dataFailure['msg'] = '密码格式不正确！支持6-32字节';
			return $dataFailure;
		}

		$codeinfo = SmsModel::getCode($phone);//response('Sms/getCode', array('phone'=>$phone));
		if($codeinfo['code'] != $code){
			$dataFailure['msg'] = '请填写正确的验证码';
			return $dataFailure;
		}
		M('t_sms_log', null, DB_MAIN_CFG)->where(" phone = '{$phone}' AND code = '{$code}' AND type = 1 AND status = 1")->save( array('status'=>2) );

		$password = passwordEncryption($password);
		$userM=M('u_user_base',null,DB_MAIN_CFG);
		$uinfo=$userM->where(" bindPhone='{$phone}' ")->find();
		if(!$uinfo){
			$dataFailure['msg']='该账号不存在！';
			return $dataFailure;
		}else{
			$data['userPWD']	= $password;
			$userM->where(" bindPhone = '{$phone}' ")->save($data);
			return array('status'=>self::SUCCESS,'msg'=>'成功');
		}
	}

	/**
	 *
	 * 修改密码
	 * $pwd1 原密码 必填
	 * $pwd2 新密码 必填
	 * $pwd3 确认密码 必填
	 * Author: Jasmine
	 * return
	 */
	public static function updatePwd($uid,$pwd1,$pwd2,$pwd3){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(!$uid || !$pwd1 || !$pwd2 || !$pwd3){
			return $dataFailure;
		}
		if(UtilsModel::strlen($pwd2) < 6 || UtilsModel::strlen($pwd2) >32 ){
			$dataFailure['msg'] = '密码格式不正确！支持6-32字节';
			return $dataFailure;
		}
		if($pwd2 != $pwd3){
			$dataFailure['msg'] = '两次密码输入不同，请重新输入';
			return $dataFailure;
		}
		$pwd1 = passwordEncryption($pwd1);
		$pwd = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$uid}")->field("userPWD")->find();

		if($pwd1 == $pwd['userPWD']){
			$data['userPWD'] = passwordEncryption($pwd3);
			$a=M('u_user_base',null,DB_MAIN_CFG)->where("uid={$uid}")->save($data);

			return $dataSuccess;
		}else{
			$dataFailure['msg'] = '原密码输入错误！';
			return $dataFailure;
		}
	}

	/**
	 *
	 * 通过验证码绑定手机号
	 * $uid 用户ID 必填
	 * phone 用户手机号码 必填
	 * code 验证码 必填
	 * $realName 真实姓名 选填
	 * Author: RickSun
	 * return
	 */
	public static function bindUserPassword($uid, $phone, $code, $realName = ''){
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(!$phone){
			return $dataFailure;
		}

		if(!filedPreMatch('phone', $phone)){
			$dataFailure['msg'] = '手机号码格式错误';
			return $dataFailure;
		}
		if(UtilsModel::strlen($code) != 4){
			$dataFailure['msg'] = '请填写正确的验证码';
			return $dataFailure;
		}
		$sms_logM = M('t_sms_log', null, DB_MAIN_CFG);
		$row = $sms_logM->where("phone = '{$phone}' AND type = 1 AND status = 1 AND code = '{$code}'")->find();

		if(!$row){
			$dataFailure['msg'] = '请填写正确的验证码';
			return $dataFailure;
		}
		$sms_logM->where("id = '{$row['id']}'")->save( array('status'=>2) );//标示为验证

		//去合并账号 丸子妈妈不需要合并账号
		//$uid = UserModel::mergeUserAccount($uid, $phone);

		$data['bindPhone'] = $phone;
		if($realName){
			$data['realName'] = $realName;
		}
		M('u_user_base', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save( $data );

		//查询是否为新绑定用户
		$operationLogM = M('u_operation_log',null,DB_MAIN_CFG);
		if($operationLogM->where("uid={$uid} and operation=".OPT_BIND_PHONE)->find()){
			//非首次绑定用户
		} else{
			//首次绑定,记录至statistic_bind_phone
			$beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
			$endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
			$bindM = M('statistic_bind_phone',null,DB_MAIN_CFG);
			if($bindM->where("addTime between {$beginToday} and {$endToday}")->find()){
				$bindM->where("addTime between {$beginToday} and {$endToday}")->setInc("bindNumber");
			} else{
				$todayFirst = array(
					'addTime'=> mktime(12,0,0,date('m'),date('d'),date('Y')),		//每天12点
					'bindNumber'=>1
				);
				$bindM->add($todayFirst);
			}
		}
		self::operationLog($uid,OPT_BIND_PHONE,$phone);	//绑定手机日志
		return UserModel::getUser($uid);

	}

	/**
	 * User: Rick.Sun.<sunwgjj@126.com>
	 * Return: void
	 * Address: 浙江宣逸网络科技有限公司
	 * @param $uid
	 * @param $phone
	 */
	private static function mergeUserAccount($uid, $phone){
		$u_user_baseM = M('u_user_base', null, DB_MAIN_CFG);
		$u_user_weixinM = M('u_user_weixin', null, DB_MAIN_CFG);
		$phoneInfo = $u_user_baseM->where(" bindPhone='{$phone}' ")->find();//已经绑定该手机号的账户
		$uidInfo = $u_user_baseM->where(" uid='{$uid}' ")->find();//当前账户

		$phoneWecahtInfo = array();
		if($phoneInfo){
			$phoneWecahtInfo = $u_user_weixinM->where(" uid='{$phoneInfo['uid']}' ")->find();//对应的微信信息
		}
		$uidWechatInfo = $u_user_weixinM->where(" uid='{$uid}' ")->find();//对应的微信信息

		//微信账号未绑定手机账号，手机账号未绑定微信账号；当进行手机绑定后，手机账号相同时，两个账号数据合并。
		if( (($phoneInfo && !$phoneWecahtInfo) && ( !$uidInfo['bindPhone'] && $uidWechatInfo))){
		//if($uid != $phoneInfo['uid'] && count($phoneWecahtInfo)<=0 && $uidWechatInfo<=0) {
			//合并余额，消费总金额，积分，经验
			$u_user_baseM->where(" uid = '{$phoneInfo['uid']}' ")
				->save(array(
					'money' => $uidInfo['money'] + $phoneInfo['money'],
					'consumeMoney' => $uidInfo['consumeMoney'] + $phoneInfo['consumeMoney'],
					'point' => $uidInfo['point'] + $phoneInfo['point'],
					'EXP' => $uidInfo['EXP'] + $phoneInfo['EXP'])
				);
			//对应参数全并日志
			MoneyModel::addLog($phoneInfo['uid'], OPT_MERGE_USER, VAL_ADD, $uidInfo['money'], intval($uidInfo['money'] + $phoneInfo['money']), 0, '合并用户' . $uid);
			PointModel::addLog($phoneInfo['uid'], OPT_MERGE_USER, VAL_ADD, $uidInfo['point'], intval($uidInfo['point'] + $phoneInfo['point']), 0, '合并用户' . $uid);
			EXPModel::addLog($phoneInfo['uid'], OPT_MERGE_USER, VAL_ADD, $uidInfo['EXP'], intval($uidInfo['EXP'] + $phoneInfo['EXP']), 0, '合并用户' . $uid);

			//签到相关数据合并
			$signM = M('u_sign',null,DB_MAIN_CFG);
			$uidSign = $signM->where(" uid='{$uid}' ")->find();
			$phoneSign = $signM->where(" uid = '{$phoneInfo['uid']}' ")->find();
			$signData = array();
			if($uidSign){
				if($phoneSign){
					if($uidSign['signAllTimes'] > $phoneSign['signAllTimes']){
						$signData['signAllTimes'] 		= $uidSign['signAllTimes'];
						$signData['signLuckyTimes'] 	= $uidSign['signLuckyTimes'];
						$signData['monFullSignTimes'] 	= $uidSign['monFullSignTimes'];
						$signData['specialLuckyTimes'] 	= $uidSign['specialLuckyTimes'];
						$signData['usedTimes'] 			= $uidSign['usedTimes'];
					}
					if($uidSign['todaySignTime'] > $phoneSign['todaySignTime']){
						$signData['signMonthTimes'] = $uidSign['signMonthTimes'];
						$signData['signDay'] 		= $uidSign['signDay'];
						$signData['todaySignRank'] 	= $uidSign['todaySignRank'];
						$signData['todaySignTime'] 	= $uidSign['todaySignTime'];
						$signData['continueDay'] 	= $uidSign['continueDay'];
					}
					if($signData){
						$signM->where(" uid = '{$phoneInfo['uid']}' ")->save($signData);
					}
				} else{
					$signData = $uidSign;
					$signData['uid'] = $phoneInfo['uid'];
					$signM->add($signData);
				}
			}

			//帐号合并记录至u_operation_log表
			M('u_operation_log',null,DB_MAIN_CFG)->add(array('uid'=>$phoneInfo['uid'],'operation'=>OPT_MERGE_USER,'addTime'=>time(),'remark'=>'合并用户'.$uid));


			M('u_user_weixin', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid']));//微信
			M('article', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid']));//文章
			M('friendship', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid']));//关注
			M('friendship', null, DB_MAIN_CFG)->where(" fid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid']));//粉丝
			M('collection', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid']));//收藏
			M('praise_log', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid'], 'nickname' => $phoneInfo['nickname']));//点赞

			//更新相关评论数据
			M('comment_1', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid'], 'nickname' => $phoneInfo['nickname']));//评论
			M('comment_2', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid'], 'nickname' => $phoneInfo['nickname']));//评论
			M('comment_3', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid'], 'nickname' => $phoneInfo['nickname']));//评论
			M('comment_4', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('uid' => $phoneInfo['uid'], 'nickname' => $phoneInfo['nickname']));//评论

			return $phoneInfo['uid'];
		}
		//手机号和微信账号绑定，可进行换绑，但是只取手机号，数据不合并。
		else if( $phoneInfo && $phoneWecahtInfo && $uidWechatInfo && $uid != $phoneInfo['uid'] ){
			M('u_user_base', null, DB_MAIN_CFG)->where(" uid = '{$phoneInfo['uid']}' ")->save(array('bindPhone' => ''));//换绑手机号
			M('u_user_base', null, DB_MAIN_CFG)->where(" uid = '{$uid}' ")->save(array('bindPhone' => $phone));//换绑手机号
		}
		return $uid;
	}






	/**
	 * 微信登陆,
	 * Author: RickSun
	 * @param $open_id
	 * @param $accountWechat 1服务号，2订阅号，app
	 * @param $union_id
	 * @param $nickname
	 * @param $pic
	 * @param int $sex
	 * @param string $subscribe_time
	 * @param int $uid,uid=null外部系统没有该用户，外部已经有对应用户，且该值即为对应编号
	 * @return array
	 */
	public static function wechatLogin($open_id, $accountWechat, $union_id, $nickname, $pic, $sex=3, $subscribe_time = '',$uid=0){

		$now        = time();
		$sex 		= intval($sex) ? $sex : 3;
		$nickname 	= addslashes($nickname);

		$account 	= "WX{$accountWechat}";
		if($accountWechat == 'app'){
			$account = 'app';
		}
		$u_user_weixinM = M('u_user_weixin', null, DB_MAIN_CFG);
		$u_user_baseM 	= M('u_user_base', null, DB_MAIN_CFG);

		$wxU=$u_user_weixinM->where(" {$account}_openID='{$open_id}' ")->find();
		
		$tip=null;
		if(!$wxU){
				$newUser=array(
					'nickname'=>$nickname,
					'regTime'=>$now,
					'regFrom'=>CLIENT_FROM_WX,
					'sex'=>$sex,
					'province'=>'330000',	//新用户默认选择浙江宁波
					'city'=>'330200',		//新用户默认选择浙江宁波
				);
				$uid = $u_user_baseM->add( $newUser );
				$tip = self::addUserValByAction( $uid,OPT_REGISTER );

				//新增指数对象
				$obj = array(
					'uid'		=> $uid,
					'nickname'	=> $nickname
				);
				M('statistic_user_like',null,DB_MAIN_CFG)->add($obj);
				if($accountWechat == 'app')
					$u_user_weixinM->add( array("uid"=> $uid, "{$account}_openID"=>$open_id, "app_loginTime"=>time(), 'WX_unionID'=>$union_id) );
				else
					$u_user_weixinM->add( array("uid"=> $uid, "{$account}_openID"=>$open_id, "{$account}_subscribeTime"=>$subscribe_time, 'WX_unionID'=>$union_id) );

				//保存目前图片 新账号保存头像
				UtilsModel::saveUserHeadPic(file_get_contents($pic), $uid);
		}
		else{
			$uid=$wxU['uid'];
			if($union_id && strcasecmp($wxU['WX_unionID'],$union_id)!=0){ //更新unionid
				$u_user_weixinM->where('uid='.$uid)->setField('WX_unionID',$union_id);
			}
		}
		self::addLoginLog($uid,CLIENT_FROM_WX );
		if(is_null($tip)){
			//登陆得积分判断
			$tip = self::addUserValByAction($uid,OPT_LOGIN);
		}

		$ret=array('uid'=>$uid);
		if(!is_null($tip) && $tip['status']==0){
			$ret['ext']=$tip['ext'];
		}
		return $ret;
	}

	/**
	 * UID绑定CID
	 * Author:wwl
	 */
	public static function uidBindCID($uid,$cid){
		$u_user_weixinM = M('u_user_weixin', null, DB_MAIN_CFG);
		if($u_user_weixinM->where("uid={$uid}")->find()){
			$u_user_weixinM->where("uid={$uid}")->setField('app_openID',$cid);
		} else{
			$data=	array("uid"=> $uid,"app_openID"=> $cid,"app_loginTime"=>time());
			$u_user_weixinM->add($data);
		}

		return;
	}


	/**
	 * 添加登陆日志
	 * Author: shijy
	 * @param $uid
	 * @param $clientFrom
	 * @return bool
	 */
	private static function addLoginLog($uid,$clientFrom){
		if(!$uid){
			return false;
		}
		$loginIP=get_client_ip();
		$now=time();
		$loginData=array(
			'uid'=>$uid,
			'addTime'=>$now,
			'clientFrom'=>$clientFrom,
			'loginIP'=>$loginIP
		);
		M('u_login_log',null,DB_MAIN_CFG)->add($loginData);

		$data=array(
			'lastLoginTime'=>$now,
			'lastLoginIP'=>$loginIP
		);
		self::getInstance()->where("uid={$uid}")->save($data);
		return true;
	}

	/**
	 *
	 * 添加签到日志
	 * Author: wwl
	 * @param $uid
	 * @param $point 签到奖励积分
	 * @param $signAllTimes 总签到次数
	 * @return bool
	 */
	private static function addSignLog($uid,$point,$signAllTimes){
		if(!$uid){
			return false;
		}
		$now = time();
		$data = array(
			'uid' 		=> $uid,
			'addTime'	=> $now,
			'addPoint'	=> $point,
			'signAllTimes'	=> $signAllTimes,
		);
		M('u_sign_log',null,DB_MAIN_CFG)->add($data);
		return true;
	}

	/**
	 *
	 * 更新签到排行
	 * Author:wwl
	 * @param $uid
	 * @return bool
	 */
	private static function todaySignRank($uid){
		if(!$uid){
			return false;
		}
		$now = time();
		$start = mktime(0,0,0,date("m",$now),date("d",$now),date("Y",$now));
		$end = mktime(23,59,59,date("m",$now),date("d",$now),date("Y",$now));

		$signM = M('u_sign',null,DB_MAIN_CFG);
		$maxRank = $signM->where("todaySignTime between {$start} and {$end}")->max("todaySignRank");
		$maxRank +=1;
		$signRankSet = S('signRankSet');
		if(!$signRankSet){
			$signRankSet = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='SIGN_RANK_SET'")->getField("cfgValue");
			S('signRankSet',$signRankSet);
		}
		$set = explode(',',$signRankSet);
		if($set[0]>0 && $maxRank > $set[0]){
			$maxRank += rand($set[1],$set[2]);
		}
		$signM->where("uid={$uid}")->setField("todaySignRank",$maxRank);
		return true;
	}

	/**
	 * 用户信息修改
	 * Author: shijy
	 * @param $uid
	 * @param $param array($realName,$nickName,$sex,$birthday,$province,$city,$district,$address)
	 * @return array
	 */
	public static function update($uid,$param){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$updateData = $param;
		if(!$uid){
			return $dataFailure;
		}


		if(UtilsModel::strlen($updateData['realName'])<C('NICKNAME_LENGTH_MIN') || UtilsModel::strlen($updateData['realName'])>C('NICKNAME_LENGTH_MAX')){
			$dataFailure['msg'] = '真实姓名格式错误';
			return $dataFailure;
		}
		if(UtilsModel::strlen($updateData['nickname'])<C('NICKNAME_LENGTH_MIN') || UtilsModel::strlen($updateData['nickname'])>C('NICKNAME_LENGTH_MAX')){
			$dataFailure['msg'] = '昵称长度不符合要求：'.C('NICKNAME_LENGTH_MIN').'-'.C('NICKNAME_LENGTH_MAX');
			return $dataFailure;
		}
		if(!$updateData['birthday']){
			$dataFailure['msg'] = '出生日期填写错误';
			return $dataFailure;
		}
		
		$res = self::getInstance()->where("uid={$uid}")->save($updateData);
		if($res !== false){
			if($res == 0){
				//数据没改动
				$dataSuccess['msg'] = "数据修改成功";
				return $dataSuccess;
			} else{
				return UserModel::getUser($uid);
			}
		}else{
			$dataFailure['msg'] = '数据修改失败！';
			return $dataFailure;
		}
	}

	/**
	 * 根据经验获得对应的用户等级
	 * Author: shijy
	 * @param int $EXP
	 * @return int|string
	 */
	public static function getMatchLevelByEXP($EXP=0){
		$CFG_LEVEL=C('USER_LEVEL');
		$resultLevel=1;
		foreach($CFG_LEVEL as $level=>$item){
			if($EXP>=$item['reuqire']){
				$resultLevel=$level;
			}else{
				return $resultLevel;
			}
		}
		return $resultLevel;
	}

	/**
	 * 添加积分
	 * uid 用户ID 必填
	 * Author: RickSun
	 * get 方式传递，uid,用户编号
	 * return
	 */
	public static function plusPoint($uid,$originVal,$addPoint,$act,$desc='',$objId=0){
		$field='point';
		return self::changeVal($field,VAL_ADD,$uid,$originVal,$addPoint,$act,$objId,$desc);
	}

	/**
	 * 扣减积分
	 * uid 用户ID 必填
	 * point 积分 必须
	 * act 类型 必须 100活动扣除
	 * msg 说明 可选
	 * Author: RickSun
	 * get 方式传递，uid,用户编号
	 * return true|false
	 */
	public static function minusPoint($uid,$originVal,$reducePoint,$act,$objId=0,$desc=''){
		$field='point';
		return self::changeVal($field,VAL_REDUCE,$uid,$originVal,$reducePoint,$act,$objId,$desc);
	}

	/**
	 * 添加余额
	 * uid 用户ID 必填
	 * Author: RickSun
	 * get 方式传递，uid,用户编号
	 * return
	 */
	public static function plusMoney($uid,$originVal,$addMoney,$act,$desc='',$objId=0){
		$field='money';
		return self::changeVal($field,VAL_ADD,$uid,$originVal,$addMoney,$act,$objId,$desc);
	}

	/**
	 * 扣减余额
	 * uid 用户ID 必填
	 * point 积分 必须
	 * act 类型 必须 100活动扣除
	 * msg 说明 可选
	 * Author: RickSun
	 * get 方式传递，uid,用户编号
	 * return true|false
	 */
	public static function minusMoney($uid,$originVal,$reduceMoney,$act,$objId=0,$desc=''){
		$field='money';
		return self::changeVal($field,VAL_REDUCE,$uid,$originVal,$reduceMoney,$act,$objId,$desc);
	}



	/**
	 * 添加经验
	 * uid 用户ID 必填
	 * Author: Shijy
	 * get 方式传递，uid,用户编号
	 * return
	 */
	public static function plusEXP($uid,$addVal,$act,$msg='',$objId=0){
		$field='EXP';
		return self::changeVal($field,VAL_ADD,$uid,$addVal,$act,$objId);
	}

	/**
	 * 扣减积分
	 * uid 用户ID 必填
	 * point 积分 必须
	 * act 类型 必须 100活动扣除
	 * msg 说明 可选
	 * Author: RickSun
	 * get 方式传递，uid,用户编号
	 * return true|false
	 */
	public static function minusEXP($uid,$reduceVal,$act,$objId=0){
		$field='EXP';
		return self::changeVal($field,VAL_REDUCE,$uid,$reduceVal,$act,$objId);
	}


	/**
	 * 用户积分，经验，余额等值修改
	 * 如果外部系统的当前值与本系统当前值不一致，则取最小值
	 * Author: shijy
	 * @param $typeSwitch 积分(point)，经验(EXP)，余额(money)
	 * @param $addOrReduce 增加还是减少
	 * @param $uid 用户编号
	 * @param $originVal 外部系统的当前值,当本参取值为负数时不需要同步值，当值>=0时需要进行同步
	 * @param $changeVal 变化量
	 * @param $act 行为操作，
	 * @param int $objId 操作客体对象编号
	 * @return array=array(
	 * 'status'=>0/1
	 * 'ext'=>array(
			point,积分最终值
			pointChange,积分变化值
			exp,经验最终值
			expChange,经验变化值
			money，余额最终终值
			moneyChange,余额变化值
			level:用户最终等级
	 * )
	 * )
	 *
	 */
	private static function changeVal($typeSwitch,$addOrReduce,$uid,$originVal,$changeVal,$act,$objId=0,$desc=''){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$field=$typeSwitch;

		$userM	=self::getInstance();
		$return = self::getUserChangeFul($uid);
		if($return['status']!=0){
			return $return;
		}
		$userInfo = $return['data'];
		$userLevel=$userInfo['level'];

		$modelName=ucwords($field);
		$class="\\Common\\Model\\".$modelName.'Model';

//		if($originVal>=0 && $userInfo[$field]>$originVal){
//			$userInfo[$field]=$originVal;
//			$userM->where(" uid = '{$uid}' ")->setField($field,$userInfo[$field]);
//			$class::addLog($uid,OPT_SYNC,VAL_REDUCE,0,$userInfo[$field],0,'与外系统属性不一致，取最小值');
//		}


		if($addOrReduce == VAL_REDUCE){
			if($userInfo[$field] < $changeVal){
				$dataFailure['msg']='余额不够扣减';
				return $dataFailure;
			}
			$finalVal=$userInfo[$field]-$changeVal;
			if($typeSwitch=='EXP'){
				$userLevel=self::getMatchLevelByEXP($finalVal);
			}
		}else{
			$finalVal=$userInfo[$field]+$changeVal;
			if($typeSwitch=='EXP'){
				$userLevel=self::getMatchLevelByEXP($finalVal);
			}
		}

		$updateData=array(
			'level'=>$userLevel,
			$field=>$finalVal
		);
		$result = $userM->where(" uid = '{$uid}' ")->save($updateData);

		if($result===false){
			$dataFailure['msg']='数据操作失败';
			return $dataFailure;
		}

		if(false === $class::addLog($uid,$act,$addOrReduce,$changeVal,$finalVal,$objId,$desc)){
			$dataFailure['msg']='日志添加失败';
			return $dataFailure;
		}


		$dataSuccess['ext']=array(
			$field=>$finalVal,
			$field.'Change'=>$changeVal
		);

		if($userLevel!=$userInfo['level']){
			$dataSuccess['ext']['level']=$userLevel;
		}

		session($field,$finalVal);
		return $dataSuccess;
	}


	/**
	 * 根据用户操作增加预设值，如投稿得积分，登陆得积分
	 * Author: shijy
	 * @param $uid  被操作对象的uid
	 * @param $actionSwitch
	 * @return array
	 */
	public static function addUserValByAction($uid,$actionSwitch){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$cfg=M('cfg_value_get',null,DB_MAIN_CFG)->where("action={$actionSwitch} and status=1")->find();
		if(!$cfg){
			$dataFailure['msg']='配置数据不存在';
			return $dataFailure;
		}

		$where="uid={$uid} and operation='{$actionSwitch}'";
		$now = time();
		$tipPre='';
		switch($cfg['limitType']+0){
			case self::LIMIT_TYPE_DAILY:
				$tipPre='今日';
				$beginTime = strtotime(date('Y-m-d',$now));
				break;
			case self::LIMIT_TYPE_WEEKLY:
				$tipPre='本周';
				if (date('w',$now)==1){
					$dateStr = date('Y-m-d',$now);
				}else {
					$dateStr = date('Y-m-d' , strtotime('last monday'));
				}
				$beginTime = strtotime($dateStr);
				break;
			case self::LIMIT_TYPE_MONTHLY:
				$tipPre='本月';
				$beginTime = strtotime(date('Y-m-1',$now));
				break;
			case self::LIMIT_TYPE_YEARLY:
				$tipPre='今年';
				$beginTime = strtotime(date('Y-1-1',$now));
				break;
			case self::LIMIT_TYPE_FULLLIFE:
				$beginTime=0;
				break;
		}
		$where .=" and addTime>={$beginTime}";

		$valLog=M('u_val_log',null,DB_MAIN_CFG);
		$logCount = $valLog->where($where)->count();
		if($logCount>=$cfg['limitNum']){
			$dataFailure['msg']='超过允许领取次数';
			return $dataFailure;
		}
		$logCount++;
		if($logCount==1){
			$tipPre .='首次';
		}else{
			$tipPre .='第'.$logCount.'次';
		}

		$ext=array();
		if($cfg['EXP']>0){
			$re=self::plusEXP($uid,$cfg['EXP'],$actionSwitch);
			$ext=array_merge($ext,$re['ext']);
		}
		if($cfg['point']>0){
			$re=self::plusPoint($uid,-1,$cfg['point'],$actionSwitch);
			$ext=array_merge($ext,$re['ext']);
		}


		if( true ){
			$actionStr=C('OPT_TYPE');
			$tip= $tipPre.$actionStr[$actionSwitch].'，';
			$gotStr=array();
			if(array_key_exists('pointChange',$ext)&&$ext['pointChange']>0){
				$gotStr[]='积分+'.$ext['pointChange'];
			}
			if(array_key_exists('EXPChange',$ext)&&$ext['EXPChange']>0){
				$gotStr[]='经验+'.$ext['pointChange'];
			}
			if(array_key_exists('level',$ext)){
				$gotStr[]='等级提升至'.$ext['level'];
			}
			$tip .=implode('、',$gotStr);
			if( $actionSwitch==OPT_LOGIN){
				$tip .="<br />评论，点赞，分享都有积分哦";
			}

			S('tip_'.$uid,$tip);
		}

		//插入日志
		$valLog->add(array(
			'uid'=>$uid,
			'operation'=>$actionSwitch,
			'addTime'=>$now
		));

		$dataSuccess['ext']=$ext;
		$dataSuccess['tip']=$tip;
		return $dataSuccess;
	}

	public static function getUidByWeixinOpenID($weixinOpenID){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$uid=M('u_user_weixin',null,DB_MAIN_CFG)->where("WX2_openID='{$weixinOpenID}' or WX2_openID='{$weixinOpenID}'")->getField('uid');
		if(!$uid){
			$dataFailure['msg']='没有对应的用户';
			return $dataFailure;
		}
		$dataSuccess['uid']=$uid;
		return $dataSuccess;
	}

	/**
	 * 根据用户编号获取头像路径
	 * Author: shijy
	 * @param $uid
	 * @return string
	 */
	public static function getHeadPicPath($uid){
		$name 	= $uid;
		$subDir = $uid % self::USER_HEADPIC_DEVIDE;
		return "{$subDir}/{$name}.jpg";
	}

	/**
	 * 获取完整头像显示路径
	 * Author: shijy
	 * @param $uid
	 * @return string
	 */
	public static function getHeadPicFullPath($uid){
		return USER_HEADPIC_SHOW_PATH.self::getHeadPicPath($uid);
	}

	/**
	 * 根据用户编号获取用户大转盘中奖记录
	 * author: wwl <wuwl@soe-soe.com>
	 * Return: array
	 * Address: 浙江宣逸网络科技有限公司
	 */
	public static function getLuckyPrizeLog($uid,$type=SignLuckyModel::PRIZE_TYPE_SIGN_LUCKY,$page,$pageSize=12,$from=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$uid){
			return $dataFailure;
		}
		$luckyM = M('u_lucky_log',null,DB_MAIN_CFG);
		$where = "uid={$uid} and type={$type} and prizeRank>0";
		$dataSuccess['total'] = $luckyM->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = max($page , 1);//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset=($dataSuccess['page']-1) * $pageSize;

		$data = $luckyM->where($where)->limit($offset,$pageSize)->order("addTime DESC")->select();

		if($data){
			foreach($data as $key => $val){
				switch($val['prizeRank']){
					case SignLuckyModel::LUCKY_PRIZE_NULL:
						$data[$key]['prizeRank'] = "未中奖";
						break;
					case SignLuckyModel::LUCKY_PRIZE_FIRST:
						$data[$key]['prizeRank'] = "一等奖";
						break;
					case SignLuckyModel::LUCKY_PRIZE_SECOND:
						$data[$key]['prizeRank'] = "二等奖";
						break;
					case SignLuckyModel::LUCKY_PRIZE_THIRD:
						$data[$key]['prizeRank'] = "三等奖";
						break;
					case SignLuckyModel::LUCKY_PRIZE_FORTH:
						$data[$key]['prizeRank'] = "四等奖";
						break;
					case SignLuckyModel::LUCKY_PRIZE_FIFTH:
						$data[$key]['prizeRank'] = "五等奖";
						break;
				}
				if($from == CLIENT_FROM_PC){
					$data[$key]['prizeNote'] = str_replace("<br/>",",",$val['prizeNote']);
				}

			}
		}
		$dataSuccess['data'] = $data;
		return $dataSuccess;
	}
 





	/*
	 * 通过uid判断后台角色身份信息
	 * Author:wwl
	 */
	public static function getUserRole($uid){
		$userRole = M('gm_sys_user',null,DB_GM_CFG)->where("uid={$uid}")->getField("role_id");
		return $userRole;
	}

	//查询 用户信息完善/手机绑定状态
	public static function isUserInfoPerfect($uid,$action){
		//查询功能是否开启
		$switch = M('cfg_value_get',null,DB_MAIN_CFG)->where("action={$action}")->getField('status');
		if($switch){
			//查询信息是否完善
			$status = M('u_val_log',null,DB_MAIN_CFG)->where("operation={$action} and uid={$uid}")->find();
			if($status){
				return false;
			}else{
				return true;
			}
		} else{
			return false;
		}

	}


	/**
	 * 添加OPT操作日志
	 *Author:wwl
	 */
	public static function operationLog($uid,$operation,$remark){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$uid || !$operation){
			return $dataFailure;
		}
		$data = array(
			'uid'		=> $uid,
			'operation'	=> $operation,
			'addTime'	=> time(),
			'remark'	=> $remark,
		);
		$id = M('u_operation_log',null,DB_MAIN_CFG)->add($data);
		if($id){
			return $dataSuccess;
		} else {
			return $dataFailure;
		}
	}


	/**
	 * 检查指定用户编号是否已经关注另一公众号
	 * @param $uid
	 * @return bool
	 */
	public static function checkFollow($uid){
	    return true;
		//判断是否已关注
		$weixin=M('u_user_weixin',null,DB_MAIN_CFG)->where("uid ='{$uid}'")->field('WX_unionID,WX2_openID')->find();
		$follow=M('ims_mc_mapping_fans',null,DB_OTHER_CFG)->where("unionid='{$weixin['WX_unionID']}'")->getField('follow');

		return true;
		if($follow==1){
			return true;
		}else{
			return false;
		}
	}



	public static function getBindPhone($uid){
		if($uid==session('uid')){
			$phone=session('bindPhone');
			if(!$phone){
				$phone=self::getInstance()->where('uid='.$uid)->getField('bindPhone');
				session('bindPhone',$phone);
			}
		}else{
			$phone=self::getInstance()->where('uid='.$uid)->getField('bindPhone');
		}

		return $phone;

	}
}
